package cn.com.fuhuitong.main.home.ui.activity

import android.Manifest
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.Observer
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.home.adapter.FVT
import cn.com.fuhuitong.main.home.adapter.FlagshipListAdapter
import cn.com.fuhuitong.main.home.vm.FlagshipViewModel
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.main.order.ui.activity.OrderSubmitActivity
import cn.com.fuhuitong.utils.LocationUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_home_flagship_list.*

@Route(path = ARouteConstance.ACTIVITY_URL_HOME_FLAGSHIP_LIST)
class HomeFlagshipListActivity : ViewModeActivity<FlagshipViewModel>() {

    private val mCategoryId: Int
        get() = intent.getIntExtra(AppConstance.BUNDLE_CATEGORY_ID, (0))

    private var isPermission = false

    private lateinit var flagshipListAdapter: FlagshipListAdapter

    override fun viewModel(): FlagshipViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_home_flagship_list

    override fun initView() {

        image_flagship_back.setOnClickListener {
            this.finish()
        }

        this.initViewRecyclerAdapter(
            recycler_flagship_list, arrayOf(FVT.FLAGSHIP_LIST.ordinal)
        )

        delegateAdapter.addAdapter(
            FlagshipListAdapter(
                applicationContext, LinearLayoutHelper().apply {
                    setDividerHeight(resources.getDimensionPixelSize(R.dimen.dp_5))
                    paddingTop = resources.getDimensionPixelSize(R.dimen.dp_5)
                }
            ).apply {
                flagshipListAdapter = this
            }
        )
        flagshipListAdapter.setOnItemClickListener { _, _, flagshipListEntity ->
            //this.finish()
            val intent = Intent(this, OrderSubmitActivity::class.java)
            intent.putExtra("flagship_store_id", flagshipListEntity.id)
            intent.putExtra("flagship_store_name", flagshipListEntity.name)
            setResult(RESULT_OK, intent)
            this.finish()
        }

        edit_flagship_content.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                KeyboardUtils.hideSoftInput(v)
                mSearch = edit_flagship_content.text.toString()
                initData()
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
        edit_flagship_content.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrEmpty()){
                    mSearch = ""
                    initData()
                }
            }
        })

        text_flagship_apply.setOnClickListener {
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                .withSerializable(
                    AppConstance.BUNDLE_WEB_VIEW,
                    MainBean(type = WebConfig.UNKNOWN.apply {
                        desc = text_flagship_apply.text.toString()
                    }, data = text_flagship_apply.tag.toString())
                )
                .navigation()
        }
    }

    private var mSearch: String = ""

    override fun initViewMode() {
        viewModel.flagshipListDataLiveData.observe(this, Observer { response ->
            handlerResponseEmpty(
                status = response.status, message = response.statusTip,
                length = response.response?.data?.size ?: 0
            )
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
//                if (it.size == 0)
//                    return@let
                flagshipListAdapter.setAddDataNew(it)
            }
        })
        viewModel.categoryTwoLiveData.observe(this, Observer { response ->
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            text_flagship_apply.isEnabled = response.response?.data?.button?.button_switch ?: 0 == 1
            text_flagship_apply.text = response.response?.data?.button?.button_name
            text_flagship_apply.tag = response.response?.data?.button?.button_url
        })
    }

    override fun initData() {

        val rxPermission = RxPermissions(this)
        val disposable: Disposable = rxPermission.request(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
            .subscribe { permission ->
                isPermission = permission
                if (!permission) {
                    toast("请到设置中开启位置权限")
                } else {
                    val location: String = LocationUtils.getInstance().getLocations(this)
                    val lng: String = location.substring(location.indexOf(",") + 1, location.length)
                    val lat: String = location.substring(0, location.indexOf(","))
                    viewModel.flagshipIndex(search = mSearch, lat = lat, lng = lng)
                }
            }
        viewModel.dispose().add(disposable)

        if (mCategoryId != 0) {
            viewModel.indexGetTwoHomeGoods(mCategoryId)
        }
    }


}